package cc.yugu.yhdw.webserver.web.controller.security.basic;

import cc.yugu.yhdw.common.annotation.ViewModel;
import cc.yugu.yhdw.common.constant.ConstEnum;
import cc.yugu.yhdw.common.domain.basic.*;
import cc.yugu.yhdw.common.domain.hdw.AgencyInfo;
import cc.yugu.yhdw.common.domain.hdw.Battery;
import cc.yugu.yhdw.common.domain.hdw.Bicycle;
import cc.yugu.yhdw.common.entity.json.ExtResult;
import cc.yugu.yhdw.common.entity.json.PageResult;
import cc.yugu.yhdw.common.utils.HttpUtils;
import cc.yugu.yhdw.common.utils.IdUtils;
import cc.yugu.yhdw.common.utils.YhdwUtils;
import cc.yugu.yhdw.webserver.constant.AppConstEnum;
import cc.yugu.yhdw.webserver.entity.SessionUser;
import cc.yugu.yhdw.webserver.service.basic.AgentService;
import cc.yugu.yhdw.webserver.service.basic.MobileMessageTemplateService;
import cc.yugu.yhdw.webserver.service.basic.OrderIdService;
import cc.yugu.yhdw.webserver.service.basic.PassportService;
import cc.yugu.yhdw.webserver.service.hdw.AgencyService;
import cc.yugu.yhdw.webserver.service.hdw.BatteryService;
import cc.yugu.yhdw.webserver.service.hdw.BicycleService;
import cc.yugu.yhdw.webserver.web.controller.security.SecurityController;
import com.mysql.jdbc.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
/**
 * 客户控制器
 *
 * @Date:Created in 2018/7/24 10:59
 * @Author:
 * @Modified By: zjn 2018/7/24 10:59
 */
@Controller
@RequestMapping(value = "/security/basic/passport")
public class PassportController extends SecurityController {
    final static String CUSTOMER_PORTRAIT_URL = "/security/basic_upload/customer_portrait.htm";

    @Autowired
    PassportService passportService;
    @Autowired
    OrderIdService orderIdService;
    @Autowired
    BicycleService bicycleService;
    @Autowired
    BatteryService batteryService;
    @Autowired
    MobileMessageTemplateService mobileMessageTemplateService;
    //zjn :新增运营商业务和代理商业务
    @Autowired
    AgentService agentService;
    @Autowired
    AgencyService agencyService;

    @ViewModel(ViewModel.INNER_PAGE)
    @RequestMapping(value = "portrait.htm", method = RequestMethod.GET)
    public void portrait() {
    }
    /**
    * 客户头像路径
    *
    * @Param: [file, model]
    * @Return: java.lang.String
    * @Author By: zjn 2018/7/24  11:00
    */
    @RequestMapping(value = "portrait.htm", method = RequestMethod.POST)
    public String portrait(@RequestParam("file") MultipartFile file, Model model) throws IOException {
        File sourceFile = new File(getAppConfig().tempDir, IdUtils.uuid() + "." + YhdwUtils.getFileSuffix(file.getOriginalFilename()));
        YhdwUtils.makeParentDir(sourceFile);
        file.transferTo(sourceFile);
        HttpUtils.HttpResp httpResp = HttpUtils.uploadFile(getAppConfig().staticUrl + CUSTOMER_PORTRAIT_URL, sourceFile, Collections.EMPTY_MAP); //upload to static server
        if (httpResp.status / 100 == 2) {
            Map map = (Map) YhdwUtils.decodeJson(httpResp.content, Map.class);
            Map data = (Map) map.get("data");

            model.addAttribute("success", true);
            model.addAttribute("filePath", data.get("filePath"));
            model.addAttribute("fileName", data.get("fileName"));
        } else {
            model.addAttribute("success", false);
            model.addAttribute("message", "上传文件出现错误");
        }

        return "/security/basic/passport/portrait_response";
    }
    /**
    * 查询
    *
    * @Param: [id, property, value]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/24  11:00
    */
    @ResponseBody
    @ViewModel(ViewModel.JSON)
    @RequestMapping(value = "unique.htm")
    public ExtResult unique(Integer id, String property, String value) {
        return passportService.findUnique(id, property, value);
    }

    @RequestMapping(value = "index.htm")
    public void index(Model model,Integer time) {
        // 是否启用
        model.addAttribute("activeFlagList",Passport.Status.values());
        if (time != null && time.equals(1) ) {
            model.addAttribute("time", time);
        } else {
            model.addAttribute("time", 0);
        }

        model.addAttribute(MENU_CODE_NAME, AppConstEnum.Menu.MENU_01_04.getValue());
    }
    /**
    * 分页查询
    *
    * @Param: [search, request]
    * @Return: cc.yugu.yhdw.common.entity.json.PageResult
    * @Author By: zjn 2018/7/24  11:02
    */
    @RequestMapping("page.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public PageResult page(Passport search, HttpServletRequest request,Integer time) {
//        if (getSessionUser(request).getType()== User.Type.SUPPLIER.getValue()){
//            return null;
//        }
        //String createTime=new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
        Date createTime = new Date();
//        if(time==1){
//            search.setCreateTime(createTime);
//        }
        // 如果是运营商登录
        if (getSessionUser(request).getType() == User.Type.AGENT.getValue()) {
            search.setAgentId(getSessionUser(request).getAgentId());
        } else if (getSessionUser(request).getType() == User.Type.AGENCY.getValue()) {
            search.setAgencyId(getSessionUser(request).getAgencyId());
        }
        // 不能放在运营商代理商判断前面
        if(time==1){
            search.setCreateTime(createTime);
        }
        return PageResult.successResult(passportService.findPage(search));
    }

    @RequestMapping(value = "add.htm")
    public void add() {
    }
    /**
    * 页面点击修改，弹出修改页面
    * 
    * @Param: [model, id]
    * @Return: java.lang.String
    * @Author By: zjn 2018/7/24  11:03
    */ 
    @RequestMapping(value = "edit.htm")
    public String edit(Model model, int id) {
        model.addAttribute("id", id);
        return "/security/basic/passport/edit";
    }
    /**
    * 展示修改页面 基本信息
    * 
    * @Param: [model, id]
    * @Return: java.lang.String
    * @Author By: zjn 2018/7/24  11:05
    */ 
    @RequestMapping(value = "edit_basic_info.htm")
    public String editBasicInfo(Model model, int id) {
        Passport entity = passportService.find(id);
        if (entity == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        } else {
            model.addAttribute("entity", entity);
        }
        return "/security/basic/passport/edit_basic_info";
    }
    /**
    * 展示修改页面 地址簿
    * 
    * @Param: [model, id]
    * @Return: void
    * @Author By: zjn 2018/7/24  11:06
    */ 
    @RequestMapping(value = "edit_address_book.htm")
    public void editAddressBook(Model model, Integer id) {
        model.addAttribute("passportId", id);
    }
    /**
    * 新建客户
    * 
    * @Param: [entity]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/24  11:06
    */ 
    @RequestMapping("create.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public ExtResult create(Passport entity) throws IOException {
        return passportService.create(entity);
    }
    /**
    * 更新
    *
    * @Param: [entity]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/20  15:21
    */
    @RequestMapping("update_basic_info.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public ExtResult updateBasicInfo(Passport entity) throws IOException {
        // 更新客户表（新添加了：可以通过admin给客户重新指定到新的运营商和代理商旗下）
        return passportService.update(entity);
    }
    /**
    * 点击查看，弹出客户信息查看
    * 
    * @Param: [model, id, item]
    * @Return: void
    * @Author By: zjn 2018/7/24  11:07
    */ 
    @RequestMapping(value = "view.htm")
    public void view(Model model, int id, Integer item) {
        model.addAttribute("id", id);
        model.addAttribute("item", item);
    }
    /**
    * 页面点击查看，弹出查看页面 基本信息  （新增条件语句判断：在查看中查看代理商和运营商）
    * 
    * @Param: [model, id]
    * @Return: java.lang.String
    * @Author By: zjn 2018/7/24  11:09
    */ 
    @RequestMapping(value = "view_basic_info.htm")
    public String viewBasicInfo(Model model, int id) {
        Passport entity = passportService.find(id);
        AgentInfo agentInfo = null;
        AgencyInfo agencyInfo = null;

        //AgentInfo agentInfo = agentService.findAgentName(entity.getAgentId());
        //AgencyInfo agencyInfo = agentService.findAgencyName(entity.getAgencyId());
        if (entity == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        } else {

            if(entity.getAgentId()==null){
                agentInfo = null;
            }
            if(entity.getAgentId()!=null){
                agentInfo = agentService.findAgentName(entity.getAgentId());
            }
            if(entity.getAgencyId()==null){
                agencyInfo = null;
            }
            if(entity.getAgencyId()!=null){
                agencyInfo = agentService.findAgencyName(entity.getAgencyId());
            }
            model.addAttribute("agentInfo",agentInfo);
            model.addAttribute("agencyInfo",agencyInfo);
            model.addAttribute("entity", entity);
        }
        return "/security/basic/passport/view_basic_info";
    }
    /**
    * 授权登记查询
    * 
    * @Param: [model, id]
    * @Return: java.lang.String
    * @Author By: zjn 2018/7/24  11:32
    */ 
    @RequestMapping(value = "view_authorization_level.htm")
    public String viewAuthorizationLevel(Model model, int id) {
        Passport entity = passportService.find(id);
        if (entity == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        } else {
            model.addAttribute("entity", entity);
        }
        return "/security/basic/passport/view_authorization_level";
    }
    /**
    * 点击查看，展示账户历史中的交易记录
    * 
    * @Param: [model, id]
    * @Return: void
    * @Author By: zjn 2018/7/24  11:36
    */ 
    @RequestMapping(value = "view_in_out_money.htm")
    public void viewInOutMoney(Model model, int id) {
        model.addAttribute("customerId", id);
    }
    /**
    * 点击查看，展示换电记录中的 换电订单
    * 
    * @Param: [model, id]
    * @Return: void
    * @Author By: zjn 2018/7/24  11:37
    */ 
    @RequestMapping(value = "view_exchange_order.htm")
    public void viewExchangeOrder(Model model, int id) {
        model.addAttribute("customerId", id);
    }
    /**
    * 查看电动车地图中位置
    * 
    * @Param: [model, id]
    * @Return: void
    * @Author By: zjn 2018/7/24  11:38
    */ 
    @RequestMapping(value = "view_bicycle.htm")
    public void viewBicycle(Model model, int id) {
        Bicycle bicycle = bicycleService.findByCustomer(id);
        String bicycleId = null;
        Double lng = null;
        Double lat = null;
        if (bicycle != null) {
            bicycleId = bicycle.getId();
            Battery battery = batteryService.findByCustomer(id);
            if (battery != null) {
                lng=battery.getLng();
                lat=battery.getLat();
            }
        }
        model.addAttribute("bicycleId", bicycleId);
        model.addAttribute("lng", lng);
        model.addAttribute("lat", lat);
    }

    @RequestMapping(value = "view_send_wait_pay.htm")
    public void viewDeliverWaitPay(Model model, int id) {
        model.addAttribute("customerId", id);
    }
    /**
    * 查看页面 地址簿
    * 
    * @Param: [model, id]
    * @Return: void
    * @Author By: zjn 2018/7/24  11:44
    */ 
    @RequestMapping(value = "view_address_book.htm")
    public void viewAddressBook(Model model, int id) {
        model.addAttribute("passportId", id);
    }

    /**
    * 页面点击充值，弹出充值页面
    * 
    * @Param: [id, model]
    * @Return: java.lang.String
    * @Author By: zjn 2018/7/24  11:45
    */ 
    @RequestMapping(value = "recharge.htm", method = RequestMethod.GET)
    public String recharge(int id, Model model) {
        Passport entity = passportService.find(id);
        if (entity == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        } else {
            model.addAttribute("entity", entity);
        }
        return "/security/basic/passport/recharge";
    }
    /**
    * 充值短信提示
    * 
    * @Param: [id, money, httpsession]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/24  13:21
    */ 
    @RequestMapping(value = "recharge.htm", method = RequestMethod.POST)
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public ExtResult recharge(int id, float money, HttpSession httpsession) {
        SessionUser sessionUser = getSessionUser(httpsession);
        if (money > 0) {
            ExtResult result = passportService.recharge(id, money, orderIdService.newOrderId(OrderId.OrderIdType.DEPOSIT));
            if (result.isSuccess()) {
                Integer passPortAgentId = passportService.findInfo(id).getAgentId();
                if (passPortAgentId == null) {
                    passPortAgentId = MobileMessageTemplate.DEFAULT_AGENT_ID;
                }
                MobileMessageTemplate template = mobileMessageTemplateService.find(passPortAgentId, MobileMessageTemplate.Type.NEW_DEPOSIT.getValue());
                Passport customer = passportService.find(id);
                String[] variable = {
                        "money", String.format("%.2f", money), "balance", String.format("%.2f", customer.getBalance() / 100.0)
                };
                String content = template.replace(variable);

                Integer agentId = sessionUser.getAgentId() == 0 ? null : sessionUser.getAgentId();
                insertMobileMessage(agentId, MobileMessage.SourceType.DEPOSIT.getValue(), String.format("%d", customer.getId()), customer.getMobile(), content, template.getId(), MobileMessage.buildVariableJson(variable), template.getCode());
            }

            return result;
        }
        return ExtResult.failResult("金额必须是正数");
    }
}
